<template>
  <view class="home">
    <form-item :formJson="formJson" :modal="modal" @handleSubmit="handleSubmit"></form-item>
  </view>
</template>

<script setup>
  import {
    onMounted,
    ref
  } from 'vue';
  import formItem from '@/components/form-item/form-item.vue';
  import { addressDetail, create, update } from '../../../config/api';
  const props = defineProps({
    id: {
      type: [String, Number],
      default: ''
    }
  })
  const modal = ref({})
  const formJson = ref([{
    label: '姓名',
    key: 'real_name',
    type: 'text',
    placeholder: '请输入联系人姓名',
    border: true
  }, {
    label: '联系电话',
    type: 'text',
    key: 'phone',
    placeholder: '请输入联系人电话',
    maxlength: 11,
    border: true
  }, {
    label: '所在区域',
    key: 'city',
    key_text: 'address_text',
    type: 'region',
    placeholder: '请选择省市区',
    border: true,
  }, {
    label: '详细地址',
    type: 'textarea',
    placeholder: '请输入详细地址',
    labelPosition: 'top',
    key: 'detail',
    border: true
  }, {
    label: '设为默认地址',
    type: 'switch',
    key: 'is_default',
  }, ])
  if (props.id) {
    uni.setNavigationBarTitle({
      title: '编辑收货地址'
    })
  }
  onMounted(() => {
    if (props.id) _addressDetail()
  })
  // 收货地址详情
  const _addressDetail = () => {
    addressDetail({ id: props.id }).then(res => {
      console.log(res)
      modal.value = res.data
      modal.value.address_text = modal.value.city
      modal.value.province_text = modal.value.city.split('-')[0]
      modal.value.city_text = modal.value.city.split('-')[1]
      modal.value.district_text = modal.value.city.split('-')[2]
    })
  }
  // 添加或编辑地址
  const handleSubmit = (row) => {
    let area = [
      { name: row.province_text, id: row.province_id },
      { name: row.city_text, id: row.city_id },
      { name: row.district_text, id: row.district_id },
    ]
    let data = {
      real_name: row.real_name,
      phone: row.phone,
      area: JSON.stringify(area),
      detail: row.detail,
      is_default: row.is_default ?? 0
    }
    if (props.id) _update(data)
    else _create(data)
  }
  // 添加地址
  const _create = (data) => {
    create(data).then(res => {
      uni.$u.toast(res.msg)
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    })
  }
  // 编辑地址
  const _update = (data) => {
    update({ ...data, id: props.id }).then(res => {
      uni.$u.toast(res.msg)
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    })
  }
</script>
<style lang="scss" scoped>
  .home {
    padding: 0 20rpx;
    min-height: 100vh;
    background-color: #fff;
  }

  ::v-deep.u-form-item__body {
    padding: 30rpx 0 !important;
  }

  ::v-deep .u-textarea {
    background-color: #f8f8f8 !important;
    margin-top: 10rpx;
  }
</style>